class_name Enemy extends Tank

var enemy_shell := preload("res://entity/bullet/enemy_shell.tscn")

## 是否掉落buff
@export var buff_type := -1
@onready var col_fire_timer: Timer = $ColFireTimer


@onready var shell_pos: Marker2D = $Graphics/Diff/Pao/ShellPos
@onready var graphics: Node2D = $Graphics
@onready var turn_timer: Timer = $TurnTimer
@onready var turn_ray: Node2D = $TurnRay

var dir := Vector2.DOWN


func hurt(data: Node2D) -> void:
	#graphics.material.set_shader_parameter("progress", 1.0)
	if multiplayer.is_server():
		health -= data.damage
		if health <= 0: die.rpc()


@rpc("any_peer", "call_local", "reliable")
func die() -> void:
	queue_free()


func _physics_process(delta: float) -> void:
	if multiplayer.is_server():
		move(delta)



@rpc("any_peer", "call_local", "reliable")
func fire(pos: Vector2, sca: Vector2, rot: float) -> void:
	var ob := enemy_shell.instantiate()
	ob.damage = damage
	ob.shooter = self
	Global.add_scene(ob, pos, sca, rot, Game.main.get_node("World/Objects/Bullets"))



func move(_delta: float) -> void:
	if multiplayer.is_server():
		if dir.length(): 
			velocity = dir * speed
			rotation = dir.angle()
		var is_col := move_and_slide()
		
		if is_col:
			if col_fire_timer.time_left == 0: 
				fire.rpc(shell_pos.global_position, Vector2.ZERO, rotation)
				col_fire_timer.start()

			var collider := get_last_slide_collision().get_collider()
			if collider is TileMap:
				var r := randi_range(0, 1)
				## Vector2.from_angle(get_last_slide_collision().get_angle() - PI/2) 等同于 get_last_slide_collision().get_normal()
				var last_col_normal := get_last_slide_collision().get_normal()
				if not is_equal_approx(last_col_normal.angle_to(dir), PI/2):
					set_dir(last_col_normal.rotated(PI/2 if r == 0 else -PI/2))



func set_dir(direction: Vector2) -> void:
	dir = direction
	turn_timer.start()


func _on_fire_timer_timeout() -> void:
	if multiplayer.is_server():
		fire.rpc(shell_pos.global_position, Vector2.ZERO, rotation)


func _on_rand_turn_timer_timeout() -> void:
	if turn_timer.time_left == 0 and multiplayer.is_server():
		var turn_rad : Dictionary = {"Right": PI/2, "Left": -PI/2, "Back": PI}
		var turn_dir_arr: Array[float] = []
		for t: RayCast2D in turn_ray.get_children():
			if not t.is_colliding():
				turn_dir_arr.append(turn_rad[t.name])
		if turn_dir_arr.size():
			var r := randi_range(0, turn_dir_arr.size() - 1)
			var new_dir: Vector2 = dir.rotated(turn_dir_arr[r])
			set_dir(new_dir)
